#!/usr/bin/env python3
import json

def generate_configs():
    with open('blade_path_detection.json', 'r', encoding='utf-8') as f:
        results = json.load(f)

    with open('servers.json', 'r', encoding='utf-8') as f:
        original_config = json.load(f)
        all_servers = {s['host']: s for s in original_config['servers']}

    path_groups = {}
    for result in results:
        path = result['blade_path']
        if path != 'NOT_FOUND':
            if path not in path_groups:
                path_groups[path] = []
            path_groups[path].append(result['host'])

    print(f"找到 {len(path_groups)} 种不同的ChaosBlade路径配置\n")

    for idx, (path, hosts) in enumerate(sorted(path_groups.items()), 1):
        config = {
            'chaosblade_path': path,
            'servers': [all_servers[host] for host in hosts if host in all_servers]
        }

        filename = f'servers_group{idx}.json'
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(config, f, ensure_ascii=False, indent=2)

        print(f"✓ 已生成: {filename}")
        print(f"  路径: {path}")
        print(f"  服务器数: {len(config['servers'])}台")
        print(f"  使用方法: python3 server_stress_advanced.py cpu --cpu-percent 30 --config {filename}\n")

    if len(path_groups) == 1:
        common_path = list(path_groups.keys())[0]
        with open('servers.json', 'r', encoding='utf-8') as f:
            config = json.load(f)
        config['chaosblade_path'] = common_path

        with open('servers.json', 'w', encoding='utf-8') as f:
            json.dump(config, f, ensure_ascii=False, indent=2)

        print("✓ 已更新默认配置文件 servers.json")

if __name__ == '__main__':
    try:
        generate_configs()
    except FileNotFoundError:
        print("错误: 请先运行 detect_blade_path.py 检测路径")
        print("运行: python3 detect_blade_path.py")
